

var app = require('http').createServer(handler),
    io = require('socket.io')(app),
    fs = require('fs');


app.listen(3000);

function handler(req,res) {
    //console.log("dirname-->"+__dirname + '/index.html');
    fs.readFile(__dirname + '/index.html',function(err,data){
        if(err){
            res.writeHead(500);
            return res.end('index.html Loading for Error');
        }
        res.writeHead(200);
        res.end(data);
    });
}

var socketio;

io.on('connection',function (socket) {
    socketio = socket;
    socket.on('realtime',function (data) {
        console.log("from client data--->"+JSON.stringify(data));
    });
});


//////////
var base = +new Date(2014, 9, 3);
var oneDay = 24 * 3600 * 1000;
var date = [];

var data = [Math.random() * 150];
var now = new Date(base);

function addData(shift) {
    now = [now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/');
    date.push(now);
    data.push((Math.random() - 0.4) * 10 + data[data.length - 1]);

    if (shift) {
        date.shift();
        data.shift();
    }

    now = new Date(+new Date(now) + oneDay);
}

for (var i = 1; i < 100; i++) {
    addData();
}

var realtime = () => {
    addData(true);
    if(socketio) socketio.emit('realtime',{data:data,date:date});
}
setInterval(realtime,1000);
